package com.lyf.boot.web.filter;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.*;

/**
 * @author Luyufan
 * @date 2023/7/3 16:55
 */
public class AuthHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public static AuthHttpServletRequestWrapper getInstance(ServletRequest request) throws IOException {
        request.getParameterMap();
        return new AuthHttpServletRequestWrapper((HttpServletRequest)request);
    }

    private AuthHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = readBytes(request.getInputStream());
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream(){
        final ByteArrayInputStream bAis = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return bAis.read();
            }
        };
    }

    /**
     * 获取http输入流
     *
     * @param inputStream 输入流
     * @return byte[]
     */
    public byte[] readBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int length;
        byte[] bytes = new byte[1024];
        while ((length = inputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes, 0, length);
        }

        return byteArrayOutputStream.toByteArray();
    }


}
